import 'package:flutter/material.dart';
import 'editor.dart' as editor;
import 'data.dart' as data;

var TodoData = new data.TodoData(); // 实例化动态数据类
TextEditingController _input_title = TextEditingController(); // 准备获取用户输入
TextEditingController _input_body = TextEditingController();

void main(){
  runApp(const MyApp());
}

// 头图
class HomeTop1 extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return
      Container(
          alignment: Alignment.topLeft,
          padding: EdgeInsets.all(30),
          constraints: BoxConstraints.tightFor(height: 200),
          decoration:BoxDecoration(color: Colors.red),
          child:
          Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('新年快乐🥳', textAlign:TextAlign.left, style: TextStyle(color:Colors.white,fontSize:30),),
                Text('This is a simple Flutter App.', textAlign:TextAlign.left, style: TextStyle(color:Colors.white,fontSize:20),),
              ]
          )
      );
  }
}

// 确认用户操作
class ConfirmDeletion extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // AlertDialog 确认弹窗
    return AlertDialog( // 注意这里返回的是 AlertDialog，如需显示，需要调用 showDialog 方法
      title: Text('等一下'),
      content: Text('你确定你完成了吗？'),
      actions: [ // 挺奇怪的，为什么不是 child
        TextButton(
          onPressed: (){ Navigator.of(context).pop(false); }, // 关闭对话框并返回结果，调用时用异步处理下
          child: Text('取消')
        ),
        TextButton(
          onPressed: (){Navigator.of(context).pop(true);},
          child: Text('确定')
        ),
      ],
    );
  }
}

class HomeList extends StatefulWidget { // 动态组件
  @override
  _HomeList createState() => _HomeList();
}

class _HomeList extends State<HomeList>{
  void initState() { // 开始数据监听
    super.initState();
    TodoData.addListener(Refresh);
  }
  void Refresh() { // 刷新方法
    setState(() {});
  }
  Widget build(BuildContext context){
    return ListView.builder(
        shrinkWrap: true,
        itemCount: TodoData.title.length,
        itemBuilder: (BuildContext ctxt, int index){
          return CheckboxListTile(
            value: TodoData.state[index],
            // 实现确认用户操作
            onChanged: (value) async{
                var user = await showDialog(context: context, builder: (BuildContext context) => ConfirmDeletion());
                if (user == true) {
                  TodoData.state[index] = value;
                  if (TodoData.state[index] == true) {
                    TodoData.RemoveAt('title', index);
                    TodoData.RemoveAt('body', index);
                    TodoData.RemoveAt('state', index);
                } else {
                  print('取消操作');
                }
                setState(() {});
            }
            },
            title: Text(TodoData.title[index]),
            subtitle: Text(TodoData.body[index]),
          );
        }
    );
  }
}

class InputTitle extends StatelessWidget { // 标题输入框
  @override
  Widget build(BuildContext context) {
    return TextField(
      autofocus: true,
      controller: _input_title, // 监听
      decoration: InputDecoration(
        labelText: '待办标题',
        hintText: '别空着，请输入标题',
        prefixIcon: Icon(Icons.book),
      ),
    );
  }
}

class InputBody extends StatelessWidget { // 描述输入框
  @override
  Widget build(BuildContext context) {
    return TextField(
      autofocus: true,
      controller: _input_body, // 监听
      minLines: 1,
      maxLines: 20,
      decoration: InputDecoration(
          labelText: '待办描述',
          hintText: '描述一下这个待办',
          prefixIcon: Icon(Icons.add_box)
      ),
    );
  }
}

class PushButton extends StatelessWidget { // 确认按钮
  @override
  Widget build(BuildContext context) {
    return TextButton(
      child: Text('确定'),
      onPressed: () {
        TodoData.Add('title', _input_title.text);
        TodoData.Add('body', _input_body.text);
        TodoData.Add('state',false);
        Navigator.pop(context);
      },
    );
  }
}

class CreateTodo extends StatelessWidget { // 创建待办弹窗，这只是个临时方案，或许马上将被 editor.dart 代替
  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Column(
        children: [
          SizedBox(height: 20),
          Text('Create Todo',style: TextStyle(fontSize: 25),),
          SizedBox(height: 30),
          InputTitle(),
          SizedBox(height: 10),
          InputBody(),
          SizedBox(height: 30),
          PushButton(),
        ],
      ),
    );
  }
}

class AppDrawer extends StatelessWidget { // 侧边栏
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView( // 直接用 ListView，方便使用
        children: [
          DrawerHeader(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Leaf Todo', style: TextStyle(fontSize: 30),),
                Text('基于 Flutter开发，使用 Material Design 3，一个简洁的待办应用'),
              ],
            ),
          ),
          ListTile(
            leading: Icon(Icons.home),
            title: Text('主页'),
          ),
        ],
      ),
    );
  }
}

class MyApp extends StatelessWidget{
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context){
    return MaterialApp(
      title: 'Leaf ToDo',
      home: MyHomePage(),
      theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.red,), // 这个red还挺好看的（乐）
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text('Leaf ToDo'),
        centerTitle: true,
        elevation: 10,
      ),
      body: Column(
          children: <Widget>[
            //HomeTop1(),
            SizedBox(height: 20),
            HomeList(),
          ]
      ),
      // drawer: AppDrawer(),
      floatingActionButton: FloatingActionButton.extended(
        icon: Icon(Icons.add),
        label: Text('Add'),
        tooltip: 'Increment',
        onPressed: () {
          /*
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context){return CreateTodo();})
          );
          */
          showDialog(context: context, builder: (BuildContext context) => CreateTodo());
        },
      ),
      drawer: AppDrawer()
    );
  }
}